// 聊天室
const net = require('net')
let client = {}
let server = net.createServer(function(socket){
    socket.setEncoding('utf8')
    server.getConnections((err,count)=>{
        socket.write('欢迎光临聊天室，现在在线人数是'+count+'，请输入你的昵称\r\n')
    })
    // 第一步给username赋值
    let username;
    socket.on('data', function(data){
        
        data.replace(/\r\n/, '')
        if(username){
            broadcast(username, `${username}:${data}`)
        }else{
            username = data
            client[username] = socket; // 缓存用户的socket,方便以后广播用
            broadcast(username, `欢迎${username}加入聊天室`)
        }
    })
    
    socket.on('end', function(){
        broadcast(username, `欢送${username}离开聊天室`)
        client[username].destroy()
        delete client[username]
    })
})

function broadcast(username, msg){
    for(let name in client){
        if(name != username){
            client[name].write(msg + '\r\n')
        }
    }
}

server.listen(8080, ()=>{
    console.log('tcp聊天室启动成功')
})